#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
创建支付表和支付日志表
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from sqlalchemy import text

def create_payment_tables():
    """创建支付相关表"""
    app = create_app()
    
    with app.app_context():
        try:
            # 创建 payments 表
            payments_sql = """
            CREATE TABLE IF NOT EXISTS `payments` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `order_id` int(11) NOT NULL COMMENT '订单ID',
                `payment_no` varchar(64) NOT NULL COMMENT '支付流水号',
                `transaction_id` varchar(64) DEFAULT NULL COMMENT '微信支付订单号',
                `amount` decimal(10,2) NOT NULL COMMENT '支付金额',
                `payment_method` varchar(20) DEFAULT 'wechat' COMMENT '支付方式',
                `status` smallint(6) DEFAULT 0 COMMENT '支付状态: 0未支付 1支付成功 2支付失败 3已退款',
                `paid_at` datetime DEFAULT NULL COMMENT '支付时间',
                `refund_at` datetime DEFAULT NULL COMMENT '退款时间',
                `refund_amount` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
                `refund_reason` varchar(255) DEFAULT NULL COMMENT '退款原因',
                `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                PRIMARY KEY (`id`),
                UNIQUE KEY `idx_payment_no` (`payment_no`),
                UNIQUE KEY `idx_transaction_id` (`transaction_id`),
                KEY `idx_order_id` (`order_id`),
                KEY `idx_status` (`status`),
                CONSTRAINT `fk_payments_order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='支付记录表';
            """
            
            # 创建 payment_logs 表
            payment_logs_sql = """
            CREATE TABLE IF NOT EXISTS `payment_logs` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `payment_id` int(11) NOT NULL COMMENT '支付ID',
                `action` varchar(50) NOT NULL COMMENT '操作类型',
                `status` smallint(6) DEFAULT NULL COMMENT '操作状态',
                `request_data` text COMMENT '请求数据',
                `response_data` text COMMENT '响应数据',
                `error_message` text COMMENT '错误信息',
                `ip_address` varchar(45) DEFAULT NULL COMMENT 'IP地址',
                `user_agent` varchar(500) DEFAULT NULL COMMENT '用户代理',
                `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                PRIMARY KEY (`id`),
                KEY `idx_payment_id` (`payment_id`),
                KEY `idx_action` (`action`),
                KEY `idx_created_at` (`created_at`),
                CONSTRAINT `fk_payment_logs_payment_id` FOREIGN KEY (`payment_id`) REFERENCES `payments` (`id`) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='支付日志表';
            """
            
            # 执行SQL
            db.session.execute(text(payments_sql))
            print("✅ payments 表创建成功")
            
            db.session.execute(text(payment_logs_sql))
            print("✅ payment_logs 表创建成功")
            
            db.session.commit()
            print("🎉 支付表创建完成！")
            
        except Exception as e:
            db.session.rollback()
            print(f"❌ 创建支付表失败: {str(e)}")
            raise

if __name__ == '__main__':
    create_payment_tables() 